<?php

namespace app\common\service\product;
use app\common\cache\product\ShopProductTypeCache;
use app\common\model\product\ShopProductTypeModel;

/**
 * 活动分类
 */
class ShopProductTypeService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
            'id' => '',
        'title' => '',
        'code' => '',
        'is_disable' => '',
        'sort' => '',
        'remark' => '',
        'image_id' => '',
        'platform_ids'=>null,//店铺平台
        'is_default'=>0
    ];
    /**
     * 活动分类列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new ShopProductTypeModel();
        $pk = "m.".$model->getPk();
        if (empty($field)) {
            $field = $pk.',title,code,is_disable,create_time,update_time,sort,remark,image_id,is_default';
        }
        if (empty($order)) {
            $order = ['sort'=>'asc',$pk => 'desc'];
        }
        $model = $model->alias('m');
        foreach ($where as $wk => $wv) {
            if ($wv[0] == 'platform_ids' && isset($wv[2])) {
                $model = $model->join('shop_product_type_attributes d', 'm.id=d.shop_product_type_id')->where('d.setting_store_platform_id', $wv[1], $wv[2]);
                unset($where[$wk]);
            }
        }


        $where = array_values($where);
        $with     = ['platforms'];
        $append   = ['platform_names','platform_ids'];
        $hidden   = ['platforms'];
        if (strpos($field, 'image_id') !== false) {
            $with[]   = $hidden[] = 'image';
            $append[] = 'image_url';
        }
        if ($page == 0 || $limit == 0) {
            return $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    /**
     * 活动分类信息
     *
     * @param int  $id   活动分类id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = ShopProductTypeCache::get($id);
        if (empty($info)) {
            $model = new ShopProductTypeModel();
            $with     = ['platforms','image'];
            $append   = ['platform_names','image_url','platform_ids'];
            $hidden   = ['platforms','image'];
            $info = $model->with($with)->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('活动分类不存在：' . $id);
                }
                return [];
            }
            $info = $info->append($append)->hidden($hidden)->toArray();
            ShopProductTypeCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 活动分类添加
     *
     * @param array $param 活动分类信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new ShopProductTypeModel();
        $pk = $model->getPk();
        unset($param[$pk]);

        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();

        // 启动事务
        $model->startTrans();
        try {
            // 添加
            $model->save($param);
            // 添加店铺平台
            if (isset($param['platform_ids'])) {
                $model->platforms()->saveAll($param['platform_ids']);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param[$pk] = $model->$pk;

        return $param;
    }
     /**
     * 活动分类修改
     *
     * @param int|array $ids   活动分类id
     * @param array     $param 活动分类信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new ShopProductTypeModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);

        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();

        // 启动事务
        $model->startTrans();
        try {
            if (is_numeric($ids)) {
                $ids = [$ids];
            }
            // 修改
            $model->where($pk, 'in', $ids)->update($param);
            if (var_isset($param, ['platform_ids'])) {
                foreach ($ids as $id) {
                    $info = $model->find($id);
                    // 修改店铺平台
                    if (isset($param['platform_ids'])) {
                        $info = $info->append(['platform_ids']);
                        relation_update($info, $info['platform_ids'], $param['platform_ids'], 'platforms');
                    }
                }
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $ids;
        ShopProductTypeCache::del($ids);
        return $param;
    }
    /**
     * 活动分类删除
     *
     * @param array $ids  活动分类id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new ShopProductTypeModel();
        $pk = $model->getPk();

        // 启动事务
        $model->startTrans();
        try {
            if (is_numeric($ids)) {
                $ids = [$ids];
            }
            if ($real) {
                foreach ($ids as $id) {
                    $info = $model->find($id);
                    // 删除平台
                    $info->platforms()->detach();
                }
                $model->where($pk, 'in', $ids)->delete();
            } else {
                $update = delete_update();
                $model->where($pk, 'in', $ids)->update($update);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $update['ids'] = $ids;
        ShopProductTypeCache::del($ids);
        return $update;
    }
}
